<template>
  <div></div>
</template>
<script>
import wx from 'weixin-js-sdk'
import { getWechatConfig, getOneApp } from 'api/home-api'
export default {
  name: 'Wx',
  data () {
    return {
      query: {
        title: '', // 分享的标题
        desc: '', // 分享的描述
        link: '', // 分享的链接
        imgUrl: '', // 分享卡片的图片
        recommend_info: ''
      }
    }
  },
  created () {
    var user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {}
    if (user['userquery'] && user['userquery'] !== -1) {
      if (user['userquery'].app_id === user['app_id']) {
        this.query = user['userquery']
        this.getAuth()
      } else {
        this.getOneApp()
      }
    } else {
      this.getOneApp()
    }
  },
  methods: {
    // 获取用户的信息
    getOneApp () {
      var user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {}
      user['userquery'] = -1
      localStorage.setItem('user', JSON.stringify(user))
      if (!user['app_id']) {
        return
      }
      const datasrc = {
        app_id: user['app_id']
      }
      const { query } = this
      getOneApp(datasrc).then(data => {
        if (data.code === 0 && data.data !== null) {
          query.title = data.data.share_title
          query.desc = data.data.share_description
          query.imgUrl = data.data.share_img
          query.recommend_info = data.data.recommend_info
          query.link = data.data.domain + '?app_id=' + user['app_id'] + '&user_id=' + user['user_id'] + '&id=' + user['id']
          query.app_id = user['app_id']
          user['userquery'] = query
          localStorage.setItem('user', JSON.stringify(user))
        }
        this.getAuth()
      }).catch(() => {
        this.getAuth()
      })
    },
    getAuth () {
      const { query } = this
      var url = ''
      if (navigator.userAgent.includes('iPhone') || navigator.userAgent.includes('iPad')) {
        url = encodeURIComponent(localStorage.getItem('originUrl'))
      } else {
        url = window.location.href.split('#')[0]
      }
      var param = { 'share_url': url } // 分享地址
      getWechatConfig(param).then(res => {
        wx.config(res.data)
        wx.ready(function () {
          wx.updateAppMessageShareData({
            title: query.title, // 分享标题
            desc: query.desc, // 分享描述
            link: query.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: query.imgUrl, // 分享图标
            success: function () {
              // 设置成功
            }
          })
          wx.updateTimelineShareData({
            title: query.title, // 分享标题
            link: query.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: query.imgUrl, // 分享图标
            success: function () {
              // 设置成功
            }
          })
        })
      }).catch(() => {
        this.$toast('授权失败')
      })
    }
  }
}
</script>
